package cn.tedu.store.service.impl;

import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import cn.tedu.store.entity.Address;
import cn.tedu.store.entity.District;
import cn.tedu.store.mapper.AddressMapper;
import cn.tedu.store.service.IAddressService;
import cn.tedu.store.service.IDistrictService;
import cn.tedu.store.service.ex.AccessDeniedException;
import cn.tedu.store.service.ex.AddressLimitExceededException;
import cn.tedu.store.service.ex.AddressNotFoundException;
import cn.tedu.store.service.ex.DeleteException;
import cn.tedu.store.service.ex.InsertException;
import cn.tedu.store.service.ex.UpdateException;
/**
 * 收货地址实现类
 * @author Administrator
 *
 */
@Service
public class AddressServiceImpl implements IAddressService {
	//可以设置的收货地址最高限制数量
	private static final int MAX_ADDRESS_COUNT=20;

	@Autowired
	private AddressMapper addressMapper;

	// TODO 自己的service只能调用自己的mapper，不能直接调用人家mapper，只能通过人家的service调用人家的mapper
	@Autowired
	private IDistrictService districtService;


	/**
	 * 创建新的收货地址
	 */
	@Override
	public void createAddress(Address address, String username) throws AddressLimitExceededException, InsertException {
		//根据参数address得到用户uid
		Integer uid = address.getUid();
		//根据uid查询收货地址数量
		Integer addressCount = addressMapper.countByUid(uid);
		//如果收货地址数量达到限制数量，抛出异常
		if(addressCount >= MAX_ADDRESS_COUNT) {
			throw new AddressLimitExceededException("您创建的收货地址已经达到最大值，每个用户最多允许创建"+MAX_ADDRESS_COUNT+"个收货地址");
		}

		//创建变量Integer isDefault 表示该地址是否为默认地址 1-是，0-不是
		Integer isDefault = addressCount==0 ? 1:0;
		address.setIsDefault(isDefault);

		
		String district = getDistrict(address.getProvince(),address.getCity(),address.getArea());
		// 封装district 省市区属性
		address.setDistrict(district);

		//将参数username(来自Session中的username)封装到address中的createdUser和modefiedUser中
		address.setCreatedUser(username);
		address.setModefiedUser(username);
		//创建当前时间，将时间封装到address的createdTime和modefiedTime中
		Date now = new Date();
		address.setCreatedTime(now);
		address.setModefiedTime(now);

		//执行增加收货地址，并返回受影响的行数
		Integer rows = addressMapper.addAddress(address);
		if(rows!=1) {
			throw new InsertException("增加收货地址出现异常!");
		}

	}


	/**
	 * 服务层，根据uid获得用户的收货地址列表，调用私有方法操作持久层
	 */
	@Override
	public List<Address> getByUid(Integer uid) {
		return findByUid(uid);
	}

	
	// 设置默认地址的实现方法
	@Override
	@Transactional //事务注解，两个以上 增/删/改 操作就要用事务注解
	public void setDefault(Integer aid, Integer uid, String username)
			throws AddressNotFoundException, AccessDeniedException,UpdateException {
		//根据aid调用私有方法查询收货地址数据
		Address address = getByAid(aid);
		if(address==null) {
			throw new AddressNotFoundException("地址不存在或已经被删除！");
		}
		
		if(address.getUid()!=uid) {
			throw new AccessDeniedException("不能修改别人的收货地址");
		}
		
		//调用私有方法将当前用户的所有地址设置为非默认
		updateNonDefault(uid);
		
		//调用私有方法将指定的收货地址设置为默认
		updateDefault(aid, username, new Date());
		
	}
	
	/**
	 * 根据aid,uid,username 删除默认地址的方法
	 */
	@Override
	@Transactional //这里有两次以上增删改操作，所以要使用事务
	public void delete(Integer aid, Integer uid, String username)
			throws AddressNotFoundException, AccessDeniedException, DeleteException, UpdateException {
		// 根据参数aid查询被删除的数据
		Address add = getByAid(aid);
	    // 判断查询结果是否为null：AddressNotFoundException
		if(add==null) {
			throw new AddressNotFoundException("要删除的地址不存在");
		}
	    // 判断查询的数据归属是否错误：AccessDeniedException
		if(add.getUid()!=uid) {
			throw new AccessDeniedException("不可以删除别人的收货地址哦");
		}
	    // 根据参数aid执行删除
		deleteByAid(aid);

	    // 判断查询结果中的`is_default`是否为0，如果是，直接return
		if(add.getIsDefault()==0) {
			return;
		}

	    // 根据参数uid查询当前用户的收货地址数量，如果为0，直接return
		if(countByUid(uid)==0) {
			return;
		}

	    // 根据参数uid查询最后修改的收货地址数据
		Address lastAdd = findLastModefied(uid);

	    // 根据以上查询的最后修改的收货地址的aid，将收货地址设置为默认
		Integer lastAid = lastAdd.getAid();
		setDefault(lastAid, uid, username);
		
	}
	
	/*根据aid删除用户收货地址*/
	private void deleteByAid(Integer aid) {
		Integer row = addressMapper.deleteByAid(aid);
		if(row!=1) {
			throw new DeleteException("删除收货地址出现异常");
		}
	}
	
	/*根据uid找到用户最后一次修改的收货地址数据*/
	private Address findLastModefied(Integer uid) {
		return addressMapper.findLastModefied(uid);
		
	}
	
	
	 /* 根据用户id统计收货地址的数量 */ 
	private Integer countByUid(Integer uid) {
		return addressMapper.countByUid(uid);
	};
	
	
	/*
	 * 将所有地址都为非默认
	 */
	private void updateNonDefault(Integer uid) {
		Integer rows = addressMapper.updateNonDefault(uid);
		if(rows==0) {
			throw new UpdateException("更新默认地址异常");
		}
	}
	/*
	 * 修改默认收货地址
	 */
	private void updateDefault(Integer aid,String modefiedUser,Date modefiedTime) {
		Integer rows = addressMapper.updataDefault(aid, modefiedUser, modefiedTime);
		if(rows!=1) {
			throw new UpdateException("更新默认地址异常");
		}
	}
	
	/*
	 * 根据地址id查询地址
	 */
	@Override
   public Address getByAid(Integer aid) {
		return addressMapper.findByAid(aid);
	}
	
	/**
	持久层根据uid查询用户的收货地址列表
	 */
	private List<Address> findByUid(Integer uid){
		return addressMapper.findByUid(uid);
	};


	/**
	 * 根据省，市，区 的代号，获取省市区的名称
	 */
	private String getDistrict(String provinceCode,String cityCode,String areaCode) {
		District province = districtService.getByCode(provinceCode);
		District city = districtService.getByCode(cityCode);
		District area = districtService.getByCode(areaCode);

		StringBuffer district = new StringBuffer();

		if(province!=null) {
			district.append(province.getName());
		}
		if(city!=null) {
			district.append(city.getName());
		}
		if(area!=null) {
			district.append(area.getName());
		}

		return district.toString();
	}









}
